#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sglib.h"
#include "lfi.h"

#define LFI_COMPARATOR(e1, e2) (strcmp(e1->filealias,e2->filealias))

SGLIB_DEFINE_LIST_PROTOTYPES(dfs_index, LFI_COMPARATOR, next)
SGLIB_DEFINE_LIST_FUNCTIONS(dfs_index, LFI_COMPARATOR, next)

/* Take a list of the local indexed files */
PUBLIC void ls_lfi(char *lfi){
    struct dfs_index *l;
    struct sglib_dfs_index_iterator it;
	memset(lfi,0,strlen(lfi));
    sprintf(lfi,"");
    if(sglib_dfs_index_len(LFIList))
        for(l=sglib_dfs_index_it_init(&it,LFIList); l!=NULL; l=sglib_dfs_index_it_next(&it))
            sprintf(lfi,"%s%s : %s\n", lfi,l->filealias,l->filepath);
}

/* Add a new file in struct dfs_index when it is indexed locally */
PUBLIC int add_to_lfi(const char *key,const char *path){
    int res;
    struct dfs_index *l_new_entry, *result;
    
    l_new_entry = malloc(sizeof(struct dfs_index));
	sprintf(l_new_entry->filealias,"%s",key);
    sprintf(l_new_entry->filepath,"%s",path);
    
    res = sglib_dfs_index_add_if_not_member(&LFIList,l_new_entry, &result);
    return res;
}

/* Remove a file from struct dfs_index */
PUBLIC int remove_from_lfi(const char *key){
    int res;
    struct dfs_index *l_new_entry, *result;
    
	l_new_entry = malloc(sizeof(struct dfs_index));
    sprintf(l_new_entry->filealias, "%s",key);

    res = sglib_dfs_index_delete_if_member(&LFIList, l_new_entry, &result);
	if(res!= 0) free(result);
    return res;
}
/* Get an entry from the LFI list*/
PUBLIC int get_entry_from_lfi(const char *key,struct dfs_index *res){
	
    struct dfs_index l_new_entry;
	struct dfs_index *r;
    
    sprintf(l_new_entry.filealias, "%s",key);
    
	if((r=sglib_dfs_index_find_member(LFIList,&l_new_entry)) != NULL){
		memcpy(res,r,sizeof(struct dfs_index));
		return OK;
	}
	return ERROR;
}
